//
//  ViewController.swift
//  ARDEMO_1
//
//  Created by 37Design on 2021/4/29.
//

import UIKit
import ARKit
import SceneKit
import TZImagePickerController
class ViewController: UIViewController, TZImagePickerControllerDelegate {
    var sceneView: SCNView = SCNView()
    var openModel = true
    
    var imagePickerVc:TZImagePickerController!

    override func viewDidLoad() {
        super.viewDidLoad()
        loadScene()
        configPicker()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.sceneView.scene?.rootNode.isPaused = true
        
    }
    
    func configPicker() {
        imagePickerVc = TZImagePickerController()
        imagePickerVc.maxImagesCount = 1 //这里设置单选
        imagePickerVc.pickerDelegate = self
    }
    
    func configSubView() {
        let arButton: UIButton = UIButton(type: UIButton.ButtonType.system)
        arButton.setTitle("AR", for: UIControl.State.normal)
        arButton.frame = CGRect(x: 20,y: 20, width: 100, height: 100)
        self.view.addSubview(arButton)
        arButton.addTarget(self, action: #selector(pushAR), for: UIControl.Event.touchUpInside)
    }
    
    @objc func pushAR(){
        let arvc :ARViewController = ARViewController()
        arvc.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.present(arvc, animated: true) {}
    }
    
    func loadScene(){
        sceneView.frame = self.view.frame
        sceneView.backgroundColor = UIColor.gray
        sceneView.allowsCameraControl = true
        sceneView.cameraControlConfiguration.allowsTranslation = false
        sceneView.cameraControlConfiguration.autoSwitchToFreeCamera = true
        self.sceneView.cameraControlConfiguration.rotationSensitivity = 0.3
        self.sceneView.showsStatistics = true
        self.view.addSubview(sceneView)
        
        /* 初始化模型 添加摄像头 */
        let baseScene: SCNScene = SCNScene(named: "Models.scnassets/盒子3.dae")!
        //动画默认关闭
        baseScene.rootNode.isPaused = openModel
        self.sceneView.scene = baseScene

        baseScene.rootNode.addChildNode(self.defaultCamera)
        self.defaultCamera.fit(to: baseScene.rootNode, with: 2.2)
        /* 灯光 */
        let lightNode = SCNNode()
        lightNode.light = SCNLight()
        lightNode.light!.type = .omni
        lightNode.scale = SCNVector3(x: 130, y: 130, z: 130)
        lightNode.position = SCNVector3(x: 0, y: 130, z: 140)
        baseScene.rootNode.addChildNode(lightNode)
//        sceneView.autoenablesDefaultLighting = true
        //添加第一个节点
//        self.addFirstNode()
        //第二个节点
//        self.addSecondNode()
        
        /* 添加手势*/
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        sceneView.addGestureRecognizer(tapGesture)
        
        #if os(macOS) || targetEnvironment(simulator)
           self.sceneView.antialiasingMode = .multisampling4X
       #else
           self.sceneView.isJitteringEnabled = true
       #endif
        configSubView()
    }
    
    func addFirstNode(){
        // 创建一个球体几何绑定到节点上去
        let node = SCNNode()
        node.name = "主要节点"
        let sphere = SCNSphere.init(radius: 0.5)
        node.position = SCNVector3Make(0, -2, 1);
        node.geometry = sphere;
        self.sceneView.scene!.rootNode.addChildNode(node)
        // 创建子节点 给子节点添加几何形状
        let childNode = SCNNode()
//        node.name = "nodeAction"
       // 设置节点的位置
       childNode.position = SCNVector3Make(-8, -5, 1);
       // 设置几何形状，选择立体字体
        let scnText = SCNText.init(string: "放大1.5倍", extrusionDepth: 0.4);
       // 设置字体颜色
        scnText.name = "tapText"
        scnText.firstMaterial?.diffuse.contents = UIColor.yellow
       // 设置字体大小
        scnText.font = UIFont.systemFont(ofSize: 3);
       // 给几点绑定几何物体
       childNode.geometry = scnText;
       node.addChildNode(childNode)
    }
    
    func addSecondNode(){
        
        let btnNode = SCNNode()
        btnNode.name = "第二个节点"
        let btnSphere = SCNSphere.init(radius: 0.5)
        btnNode.position = SCNVector3Make(-15, 4, 1);
        btnNode.geometry = btnSphere;
        self.sceneView.scene!.rootNode.addChildNode(btnNode)
        
        // 创建子节点 给子节点添加几何形状
        let childNode = SCNNode()
//        node.name = "nodeAction"
       // 设置节点的位置
       childNode.position = SCNVector3Make(8, 5, 1);
        
        let btnText = SCNText.init(string: "播放", extrusionDepth: 0.8);
        btnText.name = "动画展示"
        btnText.firstMaterial?.diffuse.contents = UIColor.yellow
        btnText.font = UIFont.systemFont(ofSize: 2);
        btnNode.geometry = btnText
        btnNode.addChildNode(childNode)
    }
    
    @objc
    func handleTap(_ gestureRecognize: UIGestureRecognizer) {
        // retrieve the SCNView
        let scnView = sceneView
        
        // check what nodes are tapped
        let p = gestureRecognize.location(in: scnView)
        let hitResults = scnView.hitTest(p, options: [:])
        // check that we clicked on at least one object
        if hitResults.count > 0 {
            // retrieved the first clicked object
            let result = hitResults[0]
            let material = result.node.geometry!.firstMaterial!
            print(result.node.name)
            if result.node.name == "Edit1" {
                //加宽
                sceneView.scene?.rootNode.shapeModelWidthWith(currentNode: sceneView.scene!.rootNode, scale: 1.3)
            }
            if result.node.name == "Edit2" {
                //加高
                sceneView.scene?.rootNode.shapemodelHeightWith(currentNode: sceneView.scene!.rootNode, scale: 1.2)
            }
            if result.node.name == "Edit3" {
                //还原
                scnView.scene?.rootNode.reduction(currentNode: scnView.scene!.rootNode)
            }
            if result.node.name == "Edit4" {
                //选取图片
                self.present(imagePickerVc, animated: true) {}
                
            }
            if result.node.name == "Edit5" {
                //改前面元素位置
                scnView.scene?.rootNode.shapeModelEditerWith(currentNode: scnView.scene!.rootNode)
            }
            // highlight
            SCNTransaction.begin()
            SCNTransaction.animationDuration = 0.5

            // on completion - unhighlight
            SCNTransaction.completionBlock = {
                SCNTransaction.begin()
                SCNTransaction.animationDuration = 0.5
                material.emission.contents = UIColor.black
                SCNTransaction.commit()
            }
            material.emission.contents = UIColor.green
            SCNTransaction.commit()
            //判断选中节点名字是否一致
            guard result.node.geometry?.name == "tapText" else {
                guard result.node.geometry?.name == "动画展示" else {
//                    result.node.scale.x = 2
//                    material.diffuse.contents = UIImage.init(named:"bg_img")
                    return
                }
                let actionText: SCNText = result.node.geometry as! SCNText
                actionText.string = "展示中"
                if openModel {
                    openModel = !openModel
                    self.sceneView.scene?.rootNode.isPaused = false
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.99) {
                        self.openModel = !self.openModel
                        self.sceneView.scene?.rootNode.isPaused = true
                        actionText.string = "重新播放"
                    }
                }
                return
            }
  
            //判断是否点击播放&暂停
            let scnText: SCNText = result.node.geometry as! SCNText
            openModel = !openModel
            
//            print("点到了展开")
//            sceneView.scene?.rootNode.isPaused = openModel
            if !openModel {
                scnText.string = "还原"
               
            }else{
                scnText.string = "放大1.5倍"
                sceneView.scene?.rootNode.reduction(currentNode: sceneView.scene!.rootNode)
            }
        }
    }
    
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        print(photos[0])
        let node = findNodeWith(name: "Front", rootNode: sceneView.scene!.rootNode)
        node.geometry?.firstMaterial?.diffuse.contents = photos[0]
    }
    //根据名称查找子节点
    func findNodeWith(name: String, rootNode: SCNNode) -> SCNNode{
        var returnNode = SCNNode()
        for childNode in rootNode.childNodes {
            if childNode.name == name {
                returnNode = childNode
                break
            }
        }
        return returnNode
    }
    
    lazy var defaultCamera: SCNNode = { () -> SCNNode in
        let node = SCNNode()
        node.name = "defaultCamera"
        node.camera = SCNCamera()
        node.camera?.fieldOfView = 45
        node.camera?.automaticallyAdjustsZRange = true
        return node
    }()

}

